<template>
  <div>
    <el-card>
      <el-button type="primary" @click="addDepart">添加科室</el-button>
    </el-card>

    <el-card class="table">
      <el-table border :data="departList" max-height="540">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column
          label="科室名称"
          prop="DepartName"
          align="center"
          width="120"
        ></el-table-column>
        <el-table-column
          label="科室描述"
          prop="DepartContent"
          align="center"
          width="380"
        ></el-table-column>
        <el-table-column
          label="二级科室"
          prop="DepartName"
          align="center"
          width="380"
        >
          <template #default="{ row, index }">
            <template v-if="row.TwoDepart.length > 0">
              <el-tag
                class="tag"
                type="primary"
                v-for="item in row.TwoDepart"
                :key="item"
                >{{ item }}</el-tag
              >
            </template>
            <template v-else>暂无信息</template>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template v-slot="{ row }">
            {{ row.createAt.toString().split("T")[0] }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row, index }">
            <el-button
              type="primary"
              size="small"
              title="添加二级科室"
              icon="Plus"
              @click="addTwoDepart(row, index)"
            ></el-button>
            <el-button
              type="info"
              size="small"
              title="修改科室信息"
              icon="edit"
              @click="updateDepart(row, index)"
            ></el-button>
            <el-button
              type="danger"
              size="small"
              title="删除科室"
              icon="delete"
              @click="deleteDepart(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagin">
        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          background
          layout="prev, pager, next, jumper , total, sizes, "
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!--    
         -->
      </div>
    </el-card>
  </div>
  <el-dialog
    v-model="centerDialogVisible"
    :title="formParams._id ? '修改科室' : '添加科室'"
    width="500"
    center
    
    @close="closes "
  >
    <el-form :model="formParams" ref="form" :rules="rules">
      <el-form-item label="科室名称" prop="DepartName">
        <el-input
          placeholder="请输入科室名称"
          v-model="formParams.DepartName"
        ></el-input>
      </el-form-item>
      <el-form-item label="科室描述" prop="DepartContent">
        <el-input
          placeholder="请输入科室描述"
          type="textarea"
          v-model="formParams.DepartContent"
        ></el-input>
      </el-form-item>
    </el-form>
    <div v-if="formParams._id">
      <el-divider content-position="left">二级科室列表</el-divider>
    <el-table :data="list" border >
      <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
      <el-table-column label="科室名称"  align="center">
        <template v-slot="{row}">
         <el-tag v-if="!row.isEdit" > {{ row.depart }}</el-tag>
         <el-input ref="input" v-else @blur="blurInput(row.key)"  v-model="row.depart" placeholder="请输入科室名称"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作"  align="center">
        <template v-slot="{row}">
          <el-button type="danger" @click="delTwoDepart(row.key)" size="small" icon="delete">删除 </el-button>
          <el-button type="info" @click="updateTwoDepart(row.key)" size="small" icon="edit">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdateDepart"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
  <TwoDepart
    v-model="twoDepart"
    :twoDeparts="twoDeparts"
    :getDepartMentList="getDepartMentList"
  ></TwoDepart>
</template>

<script setup>
import { ref, onMounted, reactive , nextTick } from "vue";
import { getDepartMentListAPI, addDepartMentAPI , deleteDepartMentAPI } from "@/api/departMent";
import { ElMessage, ElMessageBox } from "element-plus";
import TwoDepart from "./TwoDepartMent/index.vue";
defineOptions({
  name: "departMent",
});
const centerDialogVisible = ref(false);
let pageNo = ref(1);
let pageSize = ref(10);
let departList = ref([]);
let twoDepart = ref(false);
let total = ref(0);
let input = ref(null)
let formParams = reactive({
  DepartName: "",
  DepartContent: "",
  TwoDepart: [],
});
let list = ref([]);
let form = ref(null);
let rules = reactive({
  DepartName: [
    { required: true, message: "请输入科室名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在2到10个字符", trigger: "blur" },
  ],
  DepartContent: [
    { required: true, message: "请输入科室描述", trigger: "blur" },
    { min: 2, max: 100, message: "长度在2到100个字符", trigger: "blur" },
  ],
});
onMounted(() => {
  getDepartMentList();
});
//删除
const deleteDepart = (row)=>{
  ElMessageBox.confirm(`您确定要删除${row.DepartName}吗?`,"警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async()=>{
    await deleteDepartMentAPI(row._id)
    ElMessage.success("删除成功")
    getDepartMentList()
  }).catch(()=>{
    ElMessage.info("已取消删除")
  })
}
const addDepart = () => {
  centerDialogVisible.value = true;
};
//获取科室列表
const getDepartMentList = async () => {
  let result = await getDepartMentListAPI({
    pageNo: pageNo.value,
    pageSize: pageSize.value,
  });
  departList.value = result.data;
  total.value = result.total;
};
//添加科室或者修改
const addOrUpdateDepart = async () => {
  await form.value.validate();
  if(formParams._id) {
    formParams.TwoDepart = list.value.map(item=>item.depart)
  }
  //调用api
  await addDepartMentAPI(formParams);
  ElMessage.success(formParams._id ? "修改成功" : "添加成功");
  //关闭对话框
  centerDialogVisible.value = false;
  //刷新列表
  getDepartMentList();
};
//打开对话框的回调

const closes = ()=>{
  form.value.resetFields();
  Object.assign(formParams,{
    _id:'',
    DepartName:'',
    DepartContent:'',
    TwoDepart:[]
  })


}
//添加二级科室
let twoDeparts = ref("");
const addTwoDepart = (row, index) => {
  twoDeparts.value = row;
  twoDepart.value = true;
};
//修改二级科室
const updateTwoDepart = (key)=>{
  //找到list中对应key的数组，并且将isEdit改成true
  list.value.find(item=>item.key===key).isEdit=true
 
  nextTick(()=>{
    input.value.focus()
  })
}
const blurInput = (key)=>{
  //找到list中对应key的数组，并且将isEdit改成false
  list.value.find(item=>item.key===key).isEdit=false
}
const handleSizeChange = () => {
  getDepartMentList();
};
const handleCurrentChange = () => {
  getDepartMentList();
};

const updateDepart = (row, index) => {
  centerDialogVisible.value = true;
 Object.assign(formParams, row);
  list.value = formParams.TwoDepart.map((item,index)=>{
    return {
      depart:item,
      key:index,
      isEdit:false
    }
  })
};
const delTwoDepart = (index)=>{
  console.log(index);
 list.value = list.value.filter(item=>{
  return item.key !== index
 })
}
defineExpose({
  getDepartMentList,
});
</script>

<style lang="scss" scoped>
.table {
  margin: 10px 0px;
  .pagin {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }
  .tag {
    margin: 5px 5px;
  }
}
</style>
